from PIL import Image, ImageDraw, ImageFont
import qrcode


def create_composite_image(text_line1, text_line2, qr_content, output_path):
    # 设置最终图片尺寸和比例 (5:3)
    final_width = 500
    final_height = int(final_width * 3 / 5)

    # 创建白色背景图片
    composite = Image.new('RGB', (final_width, final_height), 'white')
    draw = ImageDraw.Draw(composite)

    # 设置字体
    font = ImageFont.load_default(30)

    # 第一行文字 (居中) - 使用textbbox替代textsize
    text1_bbox = draw.textbbox((0, 0), text_line1, font=font)
    text1_width = text1_bbox[2] - text1_bbox[0]
    text1_height = text1_bbox[3] - text1_bbox[1]
    draw.text(((final_width - text1_width) // 2, 20),
              text_line1, font=font, fill='black')

    # 生成二维码
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    qr.add_data(qr_content)
    qr.make(fit=True)
    qr_img = qr.make_image(fill_color="black", back_color="white")

    # 计算第二行布局
    qr_size = min(final_height - text1_height - 60, final_width // 2 - 40)
    qr_img = qr_img.resize((qr_size, qr_size))

    # 放置二维码 (左侧)
    qr_position = (40, text1_height + 40)
    composite.paste(qr_img, qr_position)

    # 右侧多行文本处理
    right_text_x = qr_position[0] + qr_size + 20
    right_text_y = qr_position[1]
    right_text_width = final_width - right_text_x - 40

    # 分割文本为多行 - 使用textbbox替代textsize
    lines = []
    current_line = []
    words = text_line2.split()

    for word in words:
        test_line = ' '.join(current_line + [word])
        test_bbox = draw.textbbox((0, 0), test_line, font=font)
        test_width = test_bbox[2] - test_bbox[0]

        if test_width <= right_text_width:
            current_line.append(word)
        else:
            lines.append(' '.join(current_line))
            current_line = [word]

    if current_line:
        lines.append(' '.join(current_line))

    # 绘制右侧文本
    for line in lines:
        draw.text((right_text_x, right_text_y), line, font=font, fill='black')
        line_bbox = draw.textbbox((0, 0), line, font=font)
        line_height = line_bbox[3] - line_bbox[1]
        right_text_y += line_height + 5  # 行间距

    # 保存图片
    composite.save(output_path)
    print(f"图片已保存到: {output_path}")


# 使用示例
create_composite_image(
    text_line1="标题",
    text_line2="正文",
    qr_content="https://example.com",
    output_path="composite_image.jpg"
)